<?php
/*
 * 车型库搜索类
 * @package    auto
 * @author     yunian, mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: ad36f8cc6725fe828d6f2b0d50fcba34cd3d9c85 $
 */

/**
 * 类搜索
 * Class AutoSearchModule
 */
class AutoSearchModule extends BasicModule {

	/** @var  参数值， 用于生成当前选项的指示符 */
	private $_params;
	private $_sel;

	private $_acNum = 0;
	private $_amNum = 0;
	private $_carids;

	private $_table;
	private $_tableModel;
	private $_tableCar;

	private static $_paramOrder = 1;

	public function __construct() {
		parent::__construct();
		$this->_table      = Table::name(Table::NAME_AUTO_CATEGORY);
		$this->_tableModel = Table::name(Table::NAME_AUTO_MODEL);
		$this->_tableCar   = Table::name(Table::NAME_AUTO_RANK_CAR);

		$this->_initParams();
	}

	/**
	 * 获取所有参数
	 * @return mixed
	 */
	public function getParams() {
		return $this->_params;
	}

	/**
	 * 获取车系数量
	 * @return mixed
	 */
	public function getAcnum() {
		return $this->_acNum;
	}

	/**
	 * 获取车款数量
	 * @return mixed
	 */
	public function getAmnum() {
		return $this->_amNum;
	}

	/**
	 * 添加参数值
	 * @param $param
	 * @param $value
	 */
	public function addSel($param, $value) {
		foreach ($this->_params as $key => $_param) {
			if ($_param['short'] == $param) {
				$this->_params[$key]['value'] = $value;
				$cache                        = $_param['cache'];
				switch ($param) {
					case 'l':
						$selection = array();
						if ($value == 0) {
							$pid = 0;
						} else {
							if ($cache[$value]['child']) {
								$pid = $value;
							} else {
								$pid = intval($cache[$value]['parentid']);
							}
						}
						foreach ($cache as $v) {
							if ($v['parentid'] == $pid) {
								$selection[$v['arid']] = $v;
							}
						}
						$this->_params[$key]['selection'] = $selection;
						$this->_params[$key]['sql']       = "m.{$_param['field']} in( {$_param['cache'][$value]['arrchildid']})";
						break;
					case 'p':
						$this->_params[$key]['sql']       = $_param['cache'][$value]['sql'];
						$this->_params[$key]['selection'] = $cache;
						break;
					case 'kw':
						$this->_params[$key]['sql'] = '';
						break;
					case 'g':
						$this->_params[$key]['sql']       = "m.{$_param['field']} in( {$_param['cache'][$value]['arrchildid']})";
						foreach($cache as $cid => $item) {
							if ($item['parentid'] == '0') {
								unset($cache[$cid]);
							}
						}
						$this->_params[$key]['selection'] = $cache;
						break;
					default :
						$this->_params[$key]['sql']       = "m.{$_param['field']} in( {$_param['cache'][$value]['arrchildid']})";
						$this->_params[$key]['selection'] = $cache;
						break;
				}
			}
		}
	}


	/**
	 * 获取参数值
	 * @param $param
	 * @return bool
	 */
	public function getSel($param) {
		foreach ($this->_params as $_param) {
			if ($_param['short'] == $param) {
				if (empty($_param['value'])) {
					return false;
				} else {
					return $_param['value'];
				}
			}
		}
		return false;
	}


	/**
	 * 获取扩展表名称
	 * @param $level
	 * @return string
	 */
	public function getExtTable($level) {
		$LEVEL     = AutoCategory::getCache(AutoCategory::TYPE_LEVEL);
		$parentids = $LEVEL[$level]['arrparentid'] . ',' . $level;
		$ids       = explode(',', $parentids);
		$tempTable = '';
		if ($level == AutoCategory::LEVEL_PASSANGER || in_array(AutoCategory::LEVEL_PASSANGER, $ids)) {
			$tempTable = Table::name(Table::NAME_AUTO_MODEL_PASSENGER);
		} else if ($level == AutoCategory::LEVEL_COMMERCIAL || in_array(AutoCategory::LEVEL_COMMERCIAL, $ids)) {
			$tempTable = Table::name(Table::NAME_AUTO_MODEL_COMMERCIAL);
		} else if ($level == AutoCategory::LEVEL_RV || in_array(AutoCategory::LEVEL_RV, $ids)) {
			$tempTable = Table::name(Table::NAME_AUTO_MODEL_RV);
		}
		return $tempTable;
	}

	/**
	 * 获取相关的原始属性
	 * @param $level
	 * @return array
	 */
	public function extParams($level) {
		global $tempTable;
		$LEVEL     = AutoCategory::getCache(AutoCategory::TYPE_LEVEL);
		$parentids = $LEVEL[$level]['arrparentid'] . ',' . $level;
		$ids       = explode(',', $parentids);
		$tempTable = $this->getExtTable($level);
		if (!$tempTable) return array();
		$fields   = PCache::read('fields-' . str_replace($this->_db->getPre(), '', $tempTable) . '.php');
		$curProps = array();
		array_shift($ids);
		foreach ($fields as $v) {
			if (in_array($v['level'], $ids)) {
				$curProps[] = $v;
			}
		}
		return $curProps;
	}

	/**
	 * 生成参数SQL
	 * @return string
	 */
	public function getParamSql() {
		$sql = array();
		foreach ($this->_params as $param) {
			if ($param['value']) {
				$sql[] = $param['sql'];
			}
		}
		return implode(' and ', $sql);
	}

	/**
	 * 获取符合条件的数量
	 * @param $modelSql
	 * @param $extSql
	 */
	public function getNums($modelSql, $extSql) {
		global $page;

		$tac        = $this->_getConditions($modelSql, $extSql);
		$tables     = $tac['tables'];
		$conditions = $tac['conditions'];

		$sql = "select count(distinct(m.arcid)) as acnum, count(distinct (m.amid)) as amnum from " . implode(',', $tables) . ' where ' . implode(' and ', $conditions);

		$nums         = $this->_db->getOne($sql);
		$this->_acNum = $nums['acnum'];
		$this->_amNum = $nums['amnum'];
		$this->_pn->records($nums['acnum']);
		$this->_pn->recordsPerPage($this->_pagesize);
		$this->_pn->setPage($page);
	}

	/**
	 * 获取匹配的车系ID
	 * @param $modelSql
	 * @param $extSql
	 * @return array
	 */
	public function getCarids($modelSql, $extSql) {
		$tables   = array();
		$tables[] = " $this->_tableModel m ";

		$tac        = $this->_getConditions($modelSql, $extSql);
		$tables     = $tac['tables'];
		$conditions = $tac['conditions'];

		$sql = "select distinct(m.arcid) from " . implode(',', $tables) . ' where ' . implode(' and ', $conditions);
		$sql .= " LIMIT " . ($this->getPn()->getPage() - 1) * $this->_pagesize . ',' . $this->_pagesize;
		$this->_carids = $this->_db->getCol($sql, 'arcid');
		return $this->_carids;
	}

	/**
	 * 获取符合条件的车款详情
	 * @param $modelSql
	 * @param $extSql
	 * @return array
	 */
	public function getModelInfos($modelSql, $extSql) {

		$tac        = $this->_getConditions($modelSql, $extSql, "m.arcid in (" . implode(',', $this->_carids) . ")");
		$tables     = $tac['tables'];
		$conditions = $tac['conditions'];

		$sql = "select m.* from " . implode(',', $tables) . ' where ' . implode(' and ', $conditions);
		return $this->_db->getAll($sql);
	}

	/**
	 * 获取车系详情
	 * @return array
	 */
	public function getCarInfos() {
		$sql    = "select rc.*, c.* from  $this->_table c left join $this->_tableCar rc on  c.arid=rc.arid  where c.arid in (" . implode(',', $this->_carids) . ")";
		$arr    = array();
		$result = $this->_db->query($sql);
		while ($r = $this->_db->fetchArray($result)) {
			$arr[]          = $r;
		}
		return $arr;
	}


	/**
	 * 整合车系和扩展的参数，用于模板中队数据的调用
	 * @param $carInfos
	 * @param $extInfos
	 */
	public function mergeCarsAndExts($carInfos, $extInfos) {
		foreach ($carInfos as $key => $car) {
			if (!isset($carInfos['children'])) {
				$carInfos[$key]['children'] = array();
			}
			$carInfos[$key]['matched']  = $this->getModelMatched($extInfos, $car['arid']);
			$carInfos[$key]['children'] = __($carInfos[$key]['matched'])->groupBy('cYear');
			$carInfos[$key]['cNum'] = count($carInfos[$key]['matched']);
			$carInfos[$key]['cPrice']  = $car['pricerange'];
			$carInfos[$key]['cGearBox'] = implode(', ', array_keys(__($carInfos[$key]['matched'])->groupBy('cGearBox')));
			$carInfos[$key]['cEmission'] = implode(', ', array_keys(__($carInfos[$key]['matched'])->groupBy('cEmission')));
			$carInfos[$key]['cEngine'] = implode(', ',array_keys(__($carInfos[$key]['matched'])->groupBy('cEngine')));
			$carInfos[$key]['cLevel'] = implode(', ',array_keys(__($carInfos[$key]['matched'])->groupBy('cLevel')));
		}
		return $carInfos;
	}


	/**
	 * 获取匹配分组的车款
	 * @param $extInfos
	 * @param $arcid
	 * @return array
	 */
	public function getModelMatched($extInfos, $arcid) {
		$arr = array();
		foreach ($extInfos as $v) {
			if ($v['arcid'] == $arcid) {
				$v['cPrice']     = Auto::formatPrice($v['price']);
				$v['cYear']     = AutoCategory::getCacheItem(AutoCategory::TYPE_YEAR, $v['year']);
				$v['cGearBox']  = AutoCategory::getCacheItem(AutoCategory::TYPE_GEARBOX, $v['gearbox']);
				$v['cEmission'] = AutoCategory::getCacheItem(AutoCategory::TYPE_EMISSION, $v['emission']);
				$v['cEngine']   = AutoCategory::getCacheItem(AutoCategory::TYPE_ENGINE, $v['enginetype']);
				$v['cCountry']  = AutoCategory::getCacheItem(AutoCategory::TYPE_COUNTRY, $v['country']);
				$v['cLevel']  = AutoCategory::getCacheItem(AutoCategory::TYPE_LEVEL, $v['acid']);
				$arr[] = $v;
			}
		}
		return $arr;
	}


	/**
	 * 初始化公共参数值
	 */
	private function _initParams() {
		$this->_params             = array();
		$this->_params['level']    = $this->_initParam('l', 'level', '级别', AutoCategory::getCache(AutoCategory::TYPE_LEVEL), 'acid', '');
		$this->_params['price']    = $this->_initPriceParam();
		$this->_params['engine']   = $this->_initParam('e', 'engine', '动力类型', AutoCategory::getCache(AutoCategory::TYPE_ENGINE), 'enginetype', '');
		$this->_params['emission'] = $this->_initParam('m', 'emission', '排放标准', AutoCategory::getCache(AutoCategory::TYPE_EMISSION), 'emission', '');
		$this->_params['gearbox']  = $this->_initParam('g', 'gearbox', '变速箱', AutoCategory::getCache(AutoCategory::TYPE_GEARBOX), 'gearbox', '');
		$this->_params['country']  = $this->_initParam('o', 'country', '国别', AutoCategory::getCache(AutoCategory::TYPE_COUNTRY), 'country', '');
		$this->_params['keyword']  = $this->_initParam('kw', 'keyword', '关键词', null, 'country', '');
	}

	/**
	 * 初始化报价参数
	 * @return array
	 */
	private function _initPriceParam() {
		$cache = array(
			'10'   => array(
				'arid' => 10,
				'name' => '10万以下',
				'sql'  => 'm.price < 100000',
			),
			'15'   => array(
				'arid' => 15,
				'name' => '10-15万',
				'sql'  => '100000 < m.price and m.price < 150000',
			),
			'20'   => array(
				'arid' => 20,
				'name' => '15-20万',
				'sql'  => '150000 < m.price and m.price < 200000',
			),
			'25'   => array(
				'arid' => 25,
				'name' => '20-25万',
				'sql'  => '200000 < m.price and m.price < 250000',
			),
			'50'   => array(
				'arid' => 50,
				'name' => '25-50万',
				'sql'  => '250000 < m.price and m.price < 500000',
			),
			'100'  => array(
				'arid' => 100,
				'name' => '50-100万',
				'sql'  => '500000 < m.price and m.price < 1000000',
			),
			'500'  => array(
				'arid' => 500,
				'name' => '100万-500万',
				'sql'  => '1000000 < m.price and m.price < 5000000',
			),
			'1000' => array(
				'arid' => 1000,
				'name' => '500万以上',
				'sql'  => '5000000 < m.price',
			),
		);
		return $this->_initParam('p', 'price', '价格', $cache, 'price', $this->_sel['price'], '');
	}

	/**
	 * 初始化参数
	 * @param $short
	 * @param $long
	 * @param $desc
	 * @param $cache
	 * @param $field
	 * @param $selection
	 * @return array
	 */
	private function _initParam($short, $long, $desc, $cache, $field, $selection) {
		return array(
			'short'     => $short,
			'long'      => $long,
			'desc'      => $desc,
			'cache'     => $cache,
			'field'     => $field,
			'selection' => $selection,
			'value'     => 0,
			'order'     => self::$_paramOrder++,
		);
	}

	/**
	 * 初始化条件的函数
	 * @param        $modelSql
	 * @param        $extSql
	 * @param string $addContions
	 * @return array
	 */
	private function _getConditions($modelSql, $extSql, $addContions = '') {
		$tables     = array();
		$kw         = $this->getSel('kw');
		$conditions = array();

		$tables[]     = " $this->_tableModel m ";
		$conditions[] = 'm.issale=1 and m.status=3';
		if ($modelSql) {
			$conditions[] = $modelSql;
		}

		if ($kw) {
			$tables[]     = $this->_table . ' c ';
			$conditions[] = 'c.arid=m.arcid';
			$conditions[] = "(c.name like '%$kw%' or c.keyword like '%$kw%')";
		}

		if ($extSql) {
			$l            = $this->getSel('l');
			$tableExt     = $this->getExtTable($l);
			$tables[]     = $tableExt . ' em ';
			$conditions[] = 'm.amid=em.amid';
			$conditions[] = $extSql;
		}

		if ($addContions) {
			$conditions[] = $addContions;
		}

		return array(
			'tables'     => $tables,
			'conditions' => $conditions,
		);
	}

}